package com.pmcc.cj.service;

import com.pmcc.cj.entity.CjAreaAgency;
import com.pmcc.cj.entity.vo.AgencyVo;
import com.pmcc.cj.repository.CjAreaAgencyRepository;
import com.pmcc.cj.vo.AreaVo;
import com.pmcc.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by tomas on 2020/10/1.
 */
@Transactional
@Service
public class CjAreaAgencyService {
    @Autowired
    CjAreaAgencyRepository cjAreaAgencyRepository;

    public ResultBean queryAreaAgencyByPage(CjAreaAgency model, AntdPage antdPage){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            Page page=cjAreaAgencyRepository.findAll(this.getSpecification(model),antdPage.getPageRequest());
//            if(page != null && page.getContent().size()>0){
//                for(CjAreaAgency areaAgency: (List<CjAreaAgency>)page.getContent()){
//                    List<CjAreaAgency> list = cjAreaAgencyRepository.findByParentIdAndDelFlag(areaAgency.getId(),0);
//                    if(list != null && list.size()>0){
//                        for(CjAreaAgency cjAreaAgency: list){
//                            List<CjAreaAgency> list1 = cjAreaAgencyRepository.findByParentIdAndDelFlag(areaAgency.getId(),0);
//                            cjAreaAgency.setDetails1(list1);
//                        }
//                    }
//                    areaAgency.setDetails(list);
//                }
//            }
            resultBean.setPage(antdPage.getDefaultCurrent());
            resultBean.setTotal(page.getTotalElements());
            resultBean.setPageSize(antdPage.getPageSize());
            resultBean.setRows(page.getContent());
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public Specification<CjAreaAgency> getSpecification(CjAreaAgency model) {
        return new Specification<CjAreaAgency>() {
            @Override
            public Predicate toPredicate(Root<CjAreaAgency> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if(StringUtil.isNotEmpty(model.getParentId())){
                    list.add(builder.equal(root.get("parentId").as(String.class),  model.getParentId()));
                }
                if(StringUtil.isNotEmpty(model.getId())){
                    list.add(builder.equal(root.get("id").as(String.class),  model.getId()));
                }
                list.add(builder.equal(root.get("delFlag").as(Integer.class), 0));
                Predicate[] p = new Predicate[list.size()];
                return builder.and(list.toArray(p));
            }
        };
    }

    public ResultBean addAreaAgency(CjAreaAgency model){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            if(StringUtil.isEmpty(model.getParentId())){
                model.setParentId("root");
                model.setLevel(1);
            }else {
                CjAreaAgency areaAgency  = cjAreaAgencyRepository.findOne(model.getParentId());
                model.setLevel(areaAgency.getLevel()+1);
            }
            model.setBoActive(false);
            model.setDelFlag(0);
            model.setActivationCode(ActivationCodeUtil.getActivationCode());
            cjAreaAgencyRepository.saveAndFlush(model);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean setAreaAgency(String id, String employeeId){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjAreaAgency areaAgency = cjAreaAgencyRepository.findOne(id);
            if(areaAgency != null && areaAgency.getDelFlag() != 0){
                areaAgency.setBoActive(true);
                areaAgency.setEmployeeId(employeeId);
                areaAgency.setUseDate(new Date());
                cjAreaAgencyRepository.saveAndFlush(areaAgency);
            }else {
                resultBean.setResultCode(ResultBean.FAIL);
                resultBean.setResultDesc("无此区域机构");
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean deleteAreaAgency(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjAreaAgency areaAgency = cjAreaAgencyRepository.findOne(id);
            if(areaAgency != null){
                //假删所有的子节点
                List<CjAreaAgency> list = new ArrayList<>();
                List<CjAreaAgency> list1 = cjAreaAgencyRepository.findByParentIdAndDelFlag(id,0);
                if(list1 != null && list1.size()>0){
                    list.addAll(list1);
                    for(CjAreaAgency cjAreaAgency1:list1){
                        List<CjAreaAgency> list2 = cjAreaAgencyRepository.findByParentIdAndDelFlag(cjAreaAgency1.getId(),0);
                        if(list2 != null && list2.size()>0){
                            list.addAll(list2);
                            for(CjAreaAgency cjAreaAgency2:list2){
                                List<CjAreaAgency> list3 = cjAreaAgencyRepository.findByParentIdAndDelFlag(cjAreaAgency2.getId(),0);
                                if(list3 != null && list3.size()>0){
                                    list.addAll(list3);
                                    for(CjAreaAgency cjAreaAgency3:list3){
                                        List<CjAreaAgency> list4 = cjAreaAgencyRepository.findByParentIdAndDelFlag(cjAreaAgency3.getId(),0);
                                        if(list4 != null && list4.size()>0){
                                            list.addAll(list4);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if(list !=null && list.size()>0){
                    for(CjAreaAgency areaAgency1: list){
                        areaAgency1.setDelFlag(1);
                        cjAreaAgencyRepository.saveAndFlush(areaAgency1);
                    }
                }
                areaAgency.setDelFlag(1);
                cjAreaAgencyRepository.saveAndFlush(areaAgency);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean modifyAreaAgency(Map map){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            CjAreaAgency areaAgency = cjAreaAgencyRepository.findOne(map.get("id").toString());
            if(areaAgency!=null && areaAgency.getDelFlag()==0){
                BeanUtils.setBeanData(areaAgency, map);
                cjAreaAgencyRepository.saveAndFlush(areaAgency);
            }
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean findAreaAgency(String parentId){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            resultBean.setRows(cjAreaAgencyRepository.findByParentIdAndDelFlag(parentId,0));
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public List<AgencyVo> queryAreaAgencyTreeGrid() {
        CjAreaAgency areaAgency = new CjAreaAgency();
        areaAgency.setId("root");
        AgencyVo agencyVo = AgencyVo.getAgencyVo(areaAgency);
        AgencyVo cjAreaAgency = this.traversalOrg(agencyVo);
        return cjAreaAgency.getChildren();
    }
    public AgencyVo traversalOrg(AgencyVo model) {
        List<CjAreaAgency> list = cjAreaAgencyRepository.findByParentIdAndDelFlag(model.getId(), 0);
        List<AgencyVo> areaAgencies = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (CjAreaAgency o : list) {
                AgencyVo agencyVo = AgencyVo.getAgencyVo(o);
                AgencyVo areaAgency = this.traversalOrg(agencyVo);
                areaAgencies.add(areaAgency);
            }
            model.setChildren(areaAgencies);
        }
        return model;
    }

    /**
     * 根据父ID查询子
     * @param parentId
     * @return
     */
    public ResultBean queryArea(String parentId) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<AreaVo> list=new ArrayList<>();
            List<CjAreaAgency> clist=cjAreaAgencyRepository.findByParentIdAndDelFlag(parentId,0);
            for(CjAreaAgency cjAreaAgency:clist){
                list.add(new AreaVo(cjAreaAgency.getId(),cjAreaAgency.getParentId(),cjAreaAgency.getAddress()));
            }
            resultBean.setRows(list);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
    public ResultBean queryAreaAgencyById(String id){
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            resultBean.setObject(cjAreaAgencyRepository.findOne(id));
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }
}
